﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Web.Mvc;
using EzDesk.Apps.Model.ProjectModule;
using EzDesk.Clients.DesktopWeb.ProjectService;
using EzDesk.Utility.Extensions;
using EzDesk.Utility.ServiceStatusInfo;
using EzDesk.Utility.Web.Controllers;
using EzDesk.Utility.Web.Extensions;
using EzDesk.Utility.Web.ServiceReference;
using System.Linq;

namespace EzDesk.Clients.DesktopWeb.Controllers
{
    [Authorize]
    public partial class ProjectController : EzDeskAppController
    {
        static IProjectService ProjectService
        {
            get { return ServiceReferenceFactory<IProjectService, ProjectServiceClient>.GetService(); }
        }

        #region [ Page Methods ]
        [HttpGet]
        public ActionResult DailyWork(long? time)
        {
            var isDisplayUnfinishedWorkitems = true;
            var isFuture = false;
            var date = getDateByDefault(time);

            if (date < DateTime.Now.Date)
                isDisplayUnfinishedWorkitems = false;
            if (date > DateTime.Now.Date)
                isFuture = true;

            dynamic model = new ExpandoObject();
            model.IsFuture = isFuture;

            if (isFuture == false)
            {
                var timeEopch = date.ToEpoch();
                var dailyWork = ProjectService.GetDailyWorks(CurrentUserId, date);

                model.DailyWork = dailyWork.Result.DailyWork;
                model.IsDisplayUnfinishedWorkitems = isDisplayUnfinishedWorkitems;
                model.Time = timeEopch;
            }

            return View(model);
        }


        [HttpGet]
        public ActionResult DailyWorkList(long? time, Guid? userId)
        {
            var date = getDateByDefault(time);
            if (!userId.HasValue)
            {
                userId = CurrentUserId;
            }
            var currentUser = EzApiClient.GetSimpleUserById(userId.GetValueOrDefault());

            dynamic model = new ExpandoObject();
            model.CurrentUser = currentUser;
            model.CurrentTime = date.Date;

            return View(model);
        }
        [HttpGet]
        public ActionResult DailyWorkListPerMonth(long? time)
        {
            var date = getDateByDefault(time);
            var startDate = date.AddDays(-date.Day);
            var endDate = startDate.AddMonths(1) < DateTime.Now ? startDate.AddMonths(1) : DateTime.Now;

            var viewModel = new List<dynamic>();
            var dailyWorkList = new List<dynamic>();
            var infoForCalendar = new List<dynamic>();



            var workitemsInMonth = ProjectService.GetWorkitems(CurrentUserId, null, null, true, null, null, startDate, endDate, null);


            for (var day = startDate.Date; day <= endDate.Date; day = day.AddDays(1).Date)
            {
                if (day > DateTime.Now.Date) continue;
                //todo: 获取每天完成的任务列表
                var workitemPerDay = workitemsInMonth.Result.Where(workitem => workitem.FinishOn.Value.Date == day.Date);


                infoForCalendar.Add(new
                {
                    Date = day.Date,
                    Title = "完成 " + workitemPerDay.Count() + " 项任务",
                });

                dailyWorkList.Add(new
                {
                    theDay = day.Date,
                    workitemList = workitemPerDay.ToList()
                });

            }

            viewModel.Add(infoForCalendar);
            viewModel.Add(dailyWorkList);

            return Json(viewModel, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult WorkitemList()
        {
            dynamic model = new ExpandoObject();
            return View(model);
        }

        [HttpGet]
        public ActionResult AddWorkitem(Guid? userId)
        {

            dynamic model = new ExpandoObject();

            var projectListModel = ProjectService.GetProjectsForUser(CurrentUserId)
                .Result
                .Select(
                    p => new
                        {
                            Name = p.Name,
                            Id = p.Id
                        }
                ).ToList();

            model.ProjectList = projectListModel;
            model.CurrentUser = EzApiClient.GetSimpleUserById(CurrentUserId);
            return View(model);
        }

        public ActionResult Workitem(Guid id)
        {
            var statusInfo = ProjectService.GetWorkitem(id);

            if (statusInfo.Status == ServiceStatus.Success)
            {
                dynamic model = new ExpandoObject();
                model.CurrentUser = EzApiClient.GetSimpleUserById(CurrentUserId);
                model.Workitem = statusInfo.Result;
                var workitem = statusInfo.Result;
                if (workitem.IsFinished)
                {
                    return View("Workitem_Finished", model);
                }
                return View(model);
            }
            // todo: 定义通用的出错页面
            throw new Exception(statusInfo.Info);
        }

        #endregion

        #region [ Ajax Methods ]


        public JsonResult OwnDailyFinishedWorkitems(long? dateTime)
        {
            DateTime date = getDateByDefault(dateTime).Date;
            var workitemList = ProjectService
                .GetWorkitems(CurrentUserId, null, null, true, null, null, date, date.AddDays(1), null)
                .Result
                .OrderByDescending(workitem => workitem.CreateOn);

            foreach (var workitem in workitemList)
            {
                workitem.OwnerName = EzApiClient.GetSimpleUserById(workitem.OwnerId).Name;
                workitem.CreatorName = EzApiClient.GetSimpleUserById(workitem.CreatorId).Name;
            }


            return Json(workitemList, JsonRequestBehavior.AllowGet);
        }

        public JsonResult OwnUnfinishedWorkitems()
        {

            var workitemList = ProjectService
                .GetWorkitems(CurrentUserId, null, null, false, null, null, null, null, null)
                .Result
                .OrderByDescending(workitem => workitem.CreateOn);

            foreach (var workitem in workitemList)
            {
                workitem.OwnerName = EzApiClient.GetSimpleUserById(workitem.OwnerId).Name;
                workitem.CreatorName = EzApiClient.GetSimpleUserById(workitem.CreatorId).Name;
            }
            return Json(workitemList, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 返回某个人当前正在进行中的任务列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult OwnWorkitems()
        {
            //todo: convert To View Model
            var workitemList = ProjectService
                .GetWorkitems(CurrentUserId, null, null, false, null, null, null, null, null)
                .Result
                .OrderByDescending(workitem => workitem.CreateOn);

            foreach (var workitem in workitemList)
            {
                workitem.OwnerName = EzApiClient.GetSimpleUserById(workitem.OwnerId).Name;
                workitem.CreatorName = EzApiClient.GetSimpleUserById(workitem.CreatorId).Name;
            }


            return Json(workitemList, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 返回某个人指派的任务列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult RequestedWorkitems()
        {
            //todo: convert To View Model
            var workitemList = ProjectService
                .GetWorkitems(null, CurrentUserId, null, false, null, null, null, null, null)
                .Result
                .Where(p => p.OwnerId != CurrentUserId) // 自己指派给自己的任务不算
                .OrderByDescending(workitem => workitem.CreateOn);

            foreach (var workitem in workitemList)
            {
                workitem.OwnerName = EzApiClient.GetSimpleUserById(workitem.OwnerId).Name;
                workitem.CreatorName = EzApiClient.GetSimpleUserById(workitem.CreatorId).Name;
            }

            return Json(workitemList, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult DoFinishWorkitem(Guid workitemId, int? points)
        {
            var estimatePoint = points ?? 0;
            var statusInfo = ProjectService.FinishWorkitem(workitemId, CurrentUserId, estimatePoint);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Data = new { workitemId };
                statusInfo.Info = "任务已完成";
            }
            return Json(statusInfo);
        }

        [HttpPost]
        public JsonResult DoAddWorkItem(
            string title,  // 任务内容
            Guid? ownerId,
            string description,  // 任务备注（详细描述）
            int? estimatePoint,  // 预估时间数
            Guid? projectId      //相关项目
            )
        {
            //todo: 对参数进行判错
            if (!ownerId.HasValue)
            {
                ownerId = CurrentUserId;
            }
            var workitem = new Workitem
                    {
                        OwnerId = ownerId.Value,
                        CreatorId = CurrentUserId,
                        CreateOn = DateTime.Now,
                        Title = title,
                        Points = estimatePoint ?? 0,
                        Description = description,
                        ProjectId = projectId
                    };
            var statusInfo = ProjectService.AddWorkitem(workitem);

            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = string.Format("添加任务“{0}”完成", title);
                statusInfo.Data = new
                                      {
                                          workitemId = statusInfo.Result
                                      };
            }
            return Json(statusInfo);
        }



        [HttpPost]
        public JsonResult DoAddFinishedWorkItem(
            string title,  // 任务内容
            string description,  // 任务备注（详细描述）
            int? estimatePoint  // 预估时间数
            )
        {
            //todo: 对参数进行判错

            var workitem = new Workitem
                               {
                                   OwnerId = CurrentUserId,
                                   CreatorId = CurrentUserId,
                                   CreateOn = DateTime.Now,
                                   Title = title,
                                   Description = description,
                                   Points = estimatePoint ?? 0,
                                   IsFinished = true,
                                   FinishOn = DateTime.Now
                               };
            var statusInfo = ProjectService.AddFinishedWorkitem(workitem);

            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = string.Format("添加任务“{0}”完成", title);
                statusInfo.Data = new
                {
                    workitemId = statusInfo.Result
                };
            }

            return Json(statusInfo);
        }

        [HttpPost]
        public ActionResult DoUpdateDailyWork(long? datetime, string dailyWorkContent)
        {
            var day = getDateByDefault(datetime);
            var statusInfo = ProjectService.UpdateDailyWorks(CurrentUserId, day.Date, dailyWorkContent);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = string.Format("工作日志日志更新完成");
            }
            return Json(statusInfo);
        }

        /// <summary>
        /// 更新项目描述
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DoUpdateDescription(Guid projectId, string description)
        {
            //todo: 换成真的
            //var statusInfo = ProjectService.UpdateDescription(projectId, description);

            var statusInfo = new StatusInfo();

            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = string.Format("更新项目描述完成");
            }

            return Json(statusInfo);
        }


        #endregion

        #region [ private method ]
        private DateTime getDateByDefault(long? time)
        {
            var date = DateTime.Now.Date;
            if (time.HasValue)
            {
                date = EpochDateTimeExtension.FromEpoch(time.Value);
            }
            return date;
        }
        #endregion
    }

}
